<template>
  <div class="cart-bottom-bar" v-show="isSettlement">
    <div class="check-content">
      <check-button
        @click.native="allClick"
        class="check-btn"
        :is-checked="isSelcetAll"
      ></check-button>
      <span>全选</span>
    </div>

    <div class="total">合计: {{ totalPrice }}</div>

    <div class="calculate" @click="calcClick">去结算({{ Settlement }})</div>
  </div>
</template>

<script>
import CheckButton from "components/content/checkButton/CheckButton";
import { mapGetters } from "vuex";

export default {
  name: "CartBottomBar",
  components: {
    CheckButton,
  },
  computed: {
    ...mapGetters(["cartList"]),
    // 计算结算价格
    totalPrice() {
      return (
        "￥" +
        this.cartList
          .filter((item) => {
            // 过滤item.checked为true
            return item.checked;
          })
          .reduce((preValue, item) => {
            // 汇总
            return preValue + item.price * item.count;
          }, 0)
          .toFixed(2)
      );
    },
    // 计算结算数量
    Settlement() {
      return this.cartList
        .filter((item) => item.checked)
        .reduce((preValue, item) => {
          return preValue + item.count;
        }, 0);
    },
    // 是否全选
    isSelcetAll() {
      if (this.cartList.length === 0) return false;

      // 如果有不被选中的(就是有长度的)就取反(false), (0取反为true 其他取反为false)
      // return !this.cartList.filter((item) => !item.checked).length;

      // 找到一个没被选中的, 就是取反变为false  性能好点不用全部遍历
      return !this.cartList.find((item) => !item.checked);
    },
    // 结算显示与否
    isSettlement() {
      if (this.cartList.length === 0) return false;
      return true;
    },
  },
  methods: {
    allClick() {
      // 全部选中
      if (this.isSelcetAll) {
        this.cartList.forEach((item) => (item.checked = false));
      } else {
        this.cartList.forEach((item) => (item.checked = true));
      }
      // 这里不能简写 一个true 另一个就为false
      // this.cartList.forEach((item) => (item.checked = !this.isSelcetAll));
    },
    calcClick() {
      // 要有一个按钮被选中才能购买
      if (this.cartList.find((item) => item.checked) !== undefined) {
        this.$toast.show("结算成功，但是请您结清账单！！", 1000);
      } else {
        this.$toast.show("购物车为空，请选择要购买的商品！", 1000);
      }
    },
  },
};
</script>

<style scoped>
.cart-bottom-bar {
  position: relative;
  display: flex;
  height: 41px;
  line-height: 40px;
  background-color: #f6f6f6;
  box-shadow: 0 -1px 1px rgba(75, 75, 75, 0.212);
}
.check-content {
  flex: 2;
  display: flex;
  align-items: center;
  margin-left: 10px;
}
.check-btn {
  width: 22px;
  height: 22px;
  line-height: 20px;
  margin-right: 8px;
}

.total {
  flex: 3;
  color: #f3491f;
  font-size: 16px;
  font-weight: 500;
}

.calculate {
  flex: 2;
  text-align: center;
  background-color: #f05e3a;
  color: #fff;
}
</style>